<script setup>
import { User, Lock } from '@element-plus/icons-vue'
import { ref, watch } from 'vue'
// 导入 userRegisterService, 用于发送注册请求
import { userRegisterService, userLoginService } from '@/api/user'
// 导入仓库
import { useUserStore } from '@/stores/modules/user'

// 导入路由
import { useRouter } from 'vue-router'

// 创建router实例
const router = useRouter()

// 创建仓库实例
const userStore = useUserStore()

// 登录注册切换
const isRegister = ref(false)

// 创建表单对象, 用于存储表单数据
const formModel = ref({
  // 表单数据
  username: '',
  password: '',
  repassword: ''
})

// 设置表单验证规则
// required: 必填项
// min: 最小长度
// max: 最大长度
// pattern: 正则表达式

// message: 错误提示信息

// trigger: 触发验证的事件
// blur: 失去焦点时触发
// change: 内容变化时触发
const rules = ref({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 10, message: '用户名长度在 3 到 10 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 16, message: '密码长度在 6 到 16 个字符', trigger: 'blur' },
    {
      pattern: /^\S{6,10}$/,
      message: '6-10位字符，且不能出现空格',
      trigger: 'blur'
    }
  ],
  repassword: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 16, message: '密码长度在 6 到 16 个字符', trigger: 'blur' },
    {
      pattern: /^\S{6,10}$/,
      message: '6-10位字符，且不能出现空格',
      trigger: 'blur'
    },
    {
      // 自定义验证器
      // 参数说明
      // rule: 当前规则
      // value: 绑定输入框的值
      // callback: 回调函数, 必须调用
      validator: (rule, value, callback) => {
        // 判断pssword 与 repassword 必须一致
        if (value !== formModel.value.password) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
})

// 获取表单对象
const form = ref()

// 注册
const register = async () => {
  // 等待表单验证
  // 校验方式: 调用 validate 方法
  await form.value.validate()
  // 验证通过, 发送请求
  await userRegisterService(formModel.value)
  ElMessage.success('注册成功')
  // 切换到登录
  isRegister.value = false
}

// 登录
const login = async () => {
  // 等待表单验证
  // 校验方式: 调用 validate 方法
  await form.value.validate()
  // 验证通过, 发送请求
  const result = await userLoginService(formModel.value)
  // 将后端返回的token保存到本地
  userStore.setToken(result.data.token)
  // 成功提示
  ElMessage.success('登录成功')
  // 切换到首页
  router.push('/')
}

// 监听切换登录注册
watch(isRegister, () => {
  // 重置表单
  formModel.value = {
    username: '',
    password: '',
    repassword: ''
  }
})
</script>

<template>
  <!--  el-row: 一行24列
        el-col: 列
        :span: 占据的宽度
        :offset: 左侧的间距

        el-form: 表单
        el-form-item: 表单项

        el-input: 输入框
        :prefix-icon: 前缀图标
        placeholder: 提示信息

        el-checkbox: 复选框
        el-link: 链接
        el-button: 按钮
-->
  <el-row class="login-page">
    <el-col :span="12" class="bg"></el-col>
    <el-col :span="6" :offset="3" class="form">
      <!-- 注册表单 -->
      <el-form
        :model="formModel"
        :rules="rules"
        ref="form"
        size="large"
        autocomplete="off"
        v-if="isRegister"
      >
        <el-form-item>
          <h1>注册</h1>
        </el-form-item>
        <el-form-item prop="username">
          <el-input
            v-model="formModel.username"
            :prefix-icon="User"
            placeholder="请输入用户名"
          ></el-input>
        </el-form-item>

        <el-form-item prop="password">
          <el-input
            v-model="formModel.password"
            :prefix-icon="Lock"
            type="password"
            placeholder="请输入密码"
          ></el-input>
        </el-form-item>
        <el-form-item prop="repassword">
          <el-input
            v-model="formModel.repassword"
            :prefix-icon="Lock"
            type="password"
            placeholder="请输入再次密码"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button
            @click="register"
            class="button"
            type="primary"
            auto-insert-space
          >
            注册
          </el-button>
        </el-form-item>
        <el-form-item class="flex">
          <el-link type="info" :underline="false" @click="isRegister = false">
            ← 返回
          </el-link>
        </el-form-item>
      </el-form>

      <!-- 登录表单 -->
      <el-form
        :model="formModel"
        :rules="rules"
        ref="form"
        size="large"
        autocomplete="off"
        v-else
      >
        <el-form-item>
          <h1>登录</h1>
        </el-form-item>
        <el-form-item>
          <el-input
            v-model="formModel.username"
            :prefix-icon="User"
            placeholder="请输入用户名"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-input
            v-model="formModel.password"
            name="password"
            :prefix-icon="Lock"
            type="password"
            placeholder="请输入密码"
          ></el-input>
        </el-form-item>
        <el-form-item class="flex">
          <div class="flex">
            <el-checkbox>记住我</el-checkbox>
            <el-link type="primary" :underline="false">忘记密码？</el-link>
          </div>
        </el-form-item>
        <el-form-item>
          <el-button
            @click="login"
            class="button"
            type="primary"
            auto-insert-space
            >登录</el-button
          >
        </el-form-item>
        <el-form-item class="flex">
          <el-link type="info" :underline="false" @click="isRegister = true">
            注册 →
          </el-link>
        </el-form-item>
      </el-form>
    </el-col>
  </el-row>
</template>

<style lang="scss" scoped>
.login-page {
  height: 100vh;
  background-color: #fff;
  .bg {
    background:
      url('@/assets/logo2.png') no-repeat 60% center / 240px auto,
      url('@/assets/login_bg.jpg') no-repeat center / cover;
    border-radius: 0 20px 20px 0;
  }
  .form {
    display: flex;
    flex-direction: column;
    justify-content: center;
    user-select: none;
    .title {
      margin: 0 auto;
    }
    .button {
      width: 100%;
    }
    .flex {
      width: 100%;
      display: flex;
      justify-content: space-between;
    }
  }
}
</style>
